/**
 * 宽带开户列表
 */
(function($) {
  var pageData = {};
  var pageCount = 1;
  var storeId = getParamValue("storeId"); //orgId
  var userId = getParamValue("userId");
  var type = getParamValue("type"); // 1 仅 校园套餐
  // var NumCode = "NA";
  // var ChannelType = "NA";
  // var prodId = "";//宽带产品标示，对应开户接口中的prod_id字段
  // var prodPrcid = "";//宽带产品资费代码，对应开户接口中的prod_prcid字段
  /*
  封装参数
  */
  var getMyParams = function() {
    var idVal = $("#broadband-id").val();
    var nameVal = $("#broadband-name").html();


    var params = "?";
    var myParam = getParams();
    if (myParam) {
      params += myParam;
      if (idVal || nameVal) {
        params += "&";
      }
    }
    if (idVal) {
      params += "id=" + idVal;
      if (nameVal) {
        params += "&";
      }
    }
    if (nameVal) {
      params += "name=" + encodeURIComponent(nameVal);
    }

    return params;
  };
  /*
  绑定事件
  */
  var bindEvent = function() {
    $("#broadband-list > li").off("click"); //取消li事件
    /*li事件*/
    $("#broadband-list > li").on("click", function() {
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";
      var $id = $("#broadband-id");
      var $name = $("#broadband-name");
      var $businessCode = $("#broadband-business-code");

      if ($siblingsNode.hasClass(primaryClass)) {
        $siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color", defaultColor);
      }
      if ($(this).hasClass(primaryClass)) {
        $(this).removeClass(primaryClass);
        $(this).css("background-color", defaultColor);
        $id.val("");
        $name.html("");
        $businessCode.val("");
      } else {
        $(this).addClass(primaryClass);
        $(this).css("background-color", selectColor);
        $id.val($(this).find("input[name='id']").val());
        $name.html($(this).find("div[name='name']").html());
        $businessCode.val($(this).find("input[name='business_code']").val());
      }
    });

    /*详情按钮*/
    $("#broadband-list > li").find(".am-badge").on("click", function(event) {
      var $id = $("#broadband-id");
      var $name = $("#broadband-name");


      var idVal = $(this).parent().find("input[name='id']").val();
      var nameVal = $(this).parent().find("div[name='name']").html();
      var broadTypeVal = $(this).parent().find("input[name='broad_type']").val();
      var business_code =  $(this).parent().find("input[name='business_code']").val();
      $id.val(idVal);
      $name.html(nameVal);
      $("#broad_type").val(broadTypeVal);

      window.location.replace("bd_openacct_detail.html" + getMyParams() + "&broad_type=" + broadTypeVal+"&business_code="+business_code+"&NumberCode="+NumCode+"&ChannelType="+ChannelType);
      event.stopPropagation();
    });
  };
  /*
  显示数据
  */
  var showDatas = function(data) {
    var $tpl = $('#amz-tpl');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
      list: data.list,
      "error": "没有宽带列表信息"
    };

    var html = template(myData);
    $tpl.before(html);

    bindEvent();
  };

  var getReqParams = function(pageNumber) {
    var params = {};
    params.pageNumber = pageNumber;
    params.pageSize = 10;
    params.storeId = storeId;
    params.type = type;

    return params;
  };

  /*
  加载数据
  */
  var loadDatas = function(pageNumber) {
    $('#modal').modal('open');
    //var params = getReqParams(pageNumber);//v1
    var params = {"pageNumber":pageNumber,"pageSize":10,"storeId":storeId,"userId":userId,"type":type};
    console.log("params = " + JSON.stringify(params));
    console.log("url = " + Constants.apiV2Host + "h5/broadband/openacct/listByType");
    $.ajax({
      //type:"post",//v1
      //url: "../../broadBandOpenAcct/listByType",//v1
      url: Constants.apiV2Host + "h5/broadband/openacct/listByType",
      data: params,
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        if (data.list instanceof Array) {
          data.list.sort(function(m, n) {
            return m.order_num - n.order_num;
          });
        }
        $('#modal').modal('close');
        $(".am-topbar").removeClass("am-hide");
        pageData = data;
        console.info(data);
        if(data.resultCode == 1001){
          showAlertMessage(data.message);
        }else{
          showDatas(data);  
        }        
      },
      error: function(textStatus) {
        $('#modal').modal('close');
        $(".am-topbar").addClass("am-hide");
        showAlertMessage("服务器请求失败，请联系管理员！");
        console.info("request error");
      }
    });
  };

  var loadStoreParams = function(){
    $.ajax({
      type: "post",
      url: "../../broadBandOpenAcct/getOrgParams?storeId="+getParamValue("storeId"),
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        console.info(data);
        if(data.ROOT.RETURN_CODE == 0){
          NumCode = data.ROOT.OUT_DATA.NumCode;
          ChannelType = data.ROOT.OUT_DATA.ChannelType;
          console.log("NumberCode="+NumCode+",ChannelType="+ChannelType);
          loadDatas(1);  
        }else{
          $('#modal').modal('close');
          showAlertMessage(data.ROOT.RETURN_MSG);
        }
      },
      error: function(textStatus) {
        console.info("request error. "+textStatus);
      }
    });
  };
  

  /**
   *判断分享出去的userId是否还有效
   **/
  var isValidUser = function() {
    $.ajax({
      type: "post",
      url: "../../broadbandH5/isValidUser",
      data: {
        "userId": getParamValue("userId")
      },
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        //console.log(data);
        if (data == "1") {
          $(".am-topbar").removeClass("am-hide");
          loadStoreParams(); 
        } else {
          $(".am-topbar").addClass("am-hide");
          showAlertMessage("店员信息已过期");
        }
      },
      error: function(textStatus) {
        $(".am-topbar").addClass("am-hide");
        showAlertMessage("服务器请求失败，请联系管理员！");
        console.info("request error");
      }
    });
  };

  var init = function(){
    var orgParams = getParamValue("orgParams");
    console.log("orgParams="+orgParams);
    if(orgParams == null){
      setCookie("orgParams", getParams(), 1);
    }
  }

  $(function() {
    console.log("type = " + getParamValue("type"));
    console.log("宽带套餐列表");
    /*滚动条*/
    var $doc = $(document);
    $doc.scroll(function() {
      //console.log("height = "+($doc.height() - $(window).height()));
      //console.log("scrollTop = "+Math.ceil($doc.scrollTop()));

      if (Math.ceil($doc.scrollTop()) >= ($doc.height() - $(window).height())) {
        var $msg = $("#no-data-msg");
        if (!$.isEmptyObject(pageData) && (pageCount < pageData.totalPage)) {
          if (!$msg.hasClass("am-hide")) {
            $msg.addClass("am-hide");
          }
          loadDatas(pageData.pageNumber + 1);
          pageCount += 1;
        } else {
          if ($msg.hasClass("am-hide")) {
            $msg.removeClass("am-hide");
          }
        }
      }
    });
    /*预约按钮*/
    $("#broadband-reservation-btn").on("click", function() {
      if (!$("#broadband-id").val() || !$("#broadband-name").html()) {
        showAlertMessage("请选择宽带套餐!");
      } else {        
        //doSRelChk($("#broadband-business-code").val());
        console.log("code:" + $("#broadband-business-code").val());
        searchProductMark($("#broadband-business-code").val(),true);
      }
    });
    init();
    /*加载模态窗口*/
    var options = {
      closeViaDimmer: false
    };
    $('#modal').modal(options);  
    //分享后的页面需要判断店员信息是否还有效
    if (getParamValue("saleType") == 2) {
      isValidUser();
    } else {         
      loadStoreParams();          
    }
  });
})(jQuery);